import { Controller } from 'egg'

function toInt(str) {
  if (typeof str === 'number')
    return str
  if (!str)
    return str
  return parseInt(str, 10) || 0
}

export default class UserController extends Controller {
  async index() {
    const ctx = this.ctx
    const query = {
      limit: toInt(ctx.query.limit),
      offset: toInt(ctx.query.offset),
    }
    ctx.body = await ctx.model.User.findAll(query)
  }

  // 查 get
  // 127.0.0.1:4000/users/:id
  async show() {
    const ctx = this.ctx
    ctx.body = await ctx.model.User.findByPk(toInt(ctx.params.id))
  }

  // 增 post
  // content-type x-www-form-urlencoded
  async create() {
    const ctx = this.ctx
    const { name, age } = ctx.request.body
    const user = await ctx.model.User.create({ name, age })
    ctx.status = 201
    ctx.body = user
  }

  // 改 put
  // 127.0.0.1:4000/users/:id
  async update() {
    const ctx = this.ctx
    const id = toInt(ctx.params.id)
    const user = await ctx.model.User.findByPk(id)
    if (!user) {
      ctx.status = 404
      return
    }

    const { name, age } = ctx.request.body
    await user.update({ name, age })
    ctx.body = user
  }

  // 删 delete
  // 127.0.0.1:4000/users/:id
  async destroy() {
    const ctx = this.ctx
    const id = toInt(ctx.params.id)
    const user = await ctx.model.User.findByPk(id)
    if (!user) {
      ctx.status = 404
      return
    }

    await user.destroy()
    ctx.status = 200
  }
}